package Avanzado.net;

import java.net.*;
import java.io.*;


public class WorkerThread extends Thread
{
	public static final int COMM_BUFFER_SIZE = 255;
	
	private Socket _client = null;
	
	private String _clientName = "";
	
	private boolean _done = false;
	
	public WorkerThread(Socket client)
	{
		_client = client;
		_clientName = _client.getRemoteSocketAddress().toString();
	}
	
	boolean isDone()
	{
		return _done;
	}
	
	public void run()
	{
		InputStreamReader in = null;
		
		try
		{
			in = new InputStreamReader(_client.getInputStream());
			
			boolean quit = false;
			
			do
			{
				char[] buffer = new char[WorkerThread.COMM_BUFFER_SIZE];
				
				int bytes = in.read(buffer, 0, WorkerThread.COMM_BUFFER_SIZE);
				
				if (bytes == -1)
				{
					System.out.println("Conexion caida!");
					quit = true;
				}
				
				String msg = new String(buffer);
				System.out.printf("<%s> dice: %s\n", _clientName, msg);
				
				if (msg.startsWith("quit"))
				{
					quit = true;
				}
				
			}
			while(!quit);
			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			try
			{
				if (in != null)
					in.close();
				
				_client.close();
				
				System.out.printf("Conexion con <%s> cerrada\n", _clientName);
				
				_done = true;
			}
			catch (Exception ex2)
			{
				ex2.printStackTrace();
			}
		}
	}

}
